<?php

// Created by Sam Starling
// sam.starling@gmail.com
// v 0.0.1 - 1 November 2009

class DailyMile {
  
  private $username;
  private $rawData;
  private $lastRun; 
  private $week;
  private $total;
  
  function __construct($username) {
    
    // Parse Javascript widget for given user
    $this->username = $username;
    $this->rawData = file_get_contents("http://www.dailymile.com/people/{$this->username}/training/widget.js");
    
    // Distance and units of most recent run
    preg_match("/.*recent_workout.*distance.*strong>(.*)\s(km|mi)<\\\\\/strong/", $this->rawData, $matches);
    if($matches) {
      $this->lastRun['distance'] = $matches[1];
      $this->lastRun['units'] = $matches [2];
    }
    
    // Duration of most recent run
    preg_match("/.*recent_workout.*\\\\\"time\\\\\">(\d?:?\d+:\d+)<\\\\\/span>.*/", $this->rawData, $matches);
    if($matches) {
      $this->lastRun['duration'] = $matches[1];
    }
    
    // Pace of most recent run
    preg_match("/.*recent_workout.*\\\\\"pace\\\\\">(\d?:?\d+:\d+) pace<\\\\\/span>.*/", $this->rawData, $matches);
    if($matches) {
      $this->lastRun['pace'] = $matches[1];
    }
    
    // Description of most recent run 
    preg_match("/.*recent_workout.*\\\\\"description\\\\\">(.*) <a.*\\\\\"timeAgo\\\\\".*/", $this->rawData, $matches);
    if($matches) {
      $this->lastRun['description'] = $matches[1];
    }
    
    // When most recent run happened
    preg_match("/.*recent_workout.*\\\\\"timeAgo\\\\\">posted (.* ago)<\\\\\/a>.*/", $this->rawData, $matches);
    if($matches) {
      $this->lastRun['timeago'] = $matches[1];
    }
    
    // Details of weekly distance
    preg_match("/.*<dd class=\\\\\"week_miles\\\\\">(\d+) <span class=\\\\\"units\\\\\">(km|mi)<\\\\\/span><\\\\\/dd>.*/", $this->rawData, $matches);
    if($matches) {
      $this->week['distance'] = $matches[1];
      $this->week['units'] = $matches[2];
    }
    
    // Details of all-time distance
    preg_match("/.*<dd class=\\\\\"total_miles\\\\\">(\d+) <span class=\\\\\"units\\\\\">(km|mi)<\\\\\/span><\\\\\/dd>.*/", $this->rawData, $matches);
    if($matches) {
      $this->total['distance'] = $matches[1];
      $this->total['units'] = $matches[2];
    }  
    
  }
  
  function getLastRun() { return $this->lastRun; }
  function getWeekTotal() { return $this->week; }
  function getTotal() { return $this->total; }
  
}

?>